﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Text.RegularExpressions;

namespace StockMentor
{
    public partial class frmFactura : Form
    {
        private SqlConnection conn;
        public static SqlConnection connStatic;
        private DataSet dsClienti, dsProduse, dsProdFact, dsFirma, dsFact;
        private SqlDataAdapter daProdFact, daFirma, daFact;
        private DataTable dtProdFact;
        private CurrencyManager crManagerProd, crManagerClienti;
        private int iNrCrt = 0;
        private double dValoareProd = 0, dValoareFaraTVA = 0, dTotalFaraTva = 0, dValoareTVA = 0, dTotalTva = 0, dTotalGeneral = 0;
        private System.Collections.ArrayList arrList = new System.Collections.ArrayList();
        private int iFactId = -1;
        private bool bModify = false;
        string sSerieNr = string.Empty;

        private static Form _singletonInstance = null;

        public frmFactura(SqlConnection conn)
        {
            InitializeComponent();
            this.conn = conn;
		
            //txtProdPret.KeyPress += new KeyPressEventHandler(text_KeyPress);
            txtProdCant.KeyPress += new KeyPressEventHandler(text_KeyPress);
        }

        void text_KeyPress(object sender, KeyPressEventArgs e)
        {
            switch (((TextBox)sender).Name)
                    {
                case "txtProdCant":

                               if (e.KeyChar != (char)Keys.Back)
                                if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
                                    e.Handled = true;
                        break;
                    
                  default:
                        break;
                    }
          //  throw new NotImplementedException();
        }

        private void btnIesire_Click(object sender, EventArgs e)
        {
            this.Close();
            gridProduseFact.Rows.Clear();
        }

        private void frmFactura_Load(object sender, EventArgs e)
        {
            CustomProcedures.conn = this.conn;

            if (!bModify)
            {
                this.Text = "Facturi - Adaugare";
                dsFirma = new DataSet();
                daFirma = new SqlDataAdapter("SELECT TOP 1 firma_cif, firma_fact_serie, firma_fact_ultimnr FROM firma ORDER BY firma_data DESC", conn);
                daFirma.Fill(dsFirma, "firma");

                txtFactSerie.Text = dsFirma.Tables["firma"].Rows[0]["firma_fact_serie"].ToString();
                txtFactNumar.Text = (Convert.ToInt32(dsFirma.Tables["firma"].Rows[0]["firma_fact_ultimnr"]) + 1).ToString();
            }
            else
            {
                this.Text = "Facturi - Modificare";
                dsFact = new DataSet();
                daFact = new SqlDataAdapter("SELECT * FROM facturi WHERE fact_id = " + iFactId.ToString(), conn); 
                daFact.Fill(dsFact, "facturi");

                txtFactSerie.Text = dsFact.Tables["facturi"].Rows[0]["fact_serie"].ToString();
                txtFactNumar.Text = dsFact.Tables["facturi"].Rows[0]["fact_numar"].ToString();
                btnNou.Visible = false;
            }

            if (!bModify)
            {
                dsProdFact = new DataSet();
                daProdFact = new SqlDataAdapter();

                dtProdFact = new DataTable("Factura_Produs");

                DataColumn cIdProd = new DataColumn("factprod_idprod", typeof(int));
                DataColumn cCant = new DataColumn("factprod_cant", typeof(int));
                DataColumn cPret = new DataColumn("factprod_pret", typeof(float));
                DataColumn cValTva = new DataColumn("factprod_val_tva", typeof(float));

                dtProdFact.Columns.Add(cIdProd);
                dtProdFact.Columns.Add(cCant);
                dtProdFact.Columns.Add(cPret);
                dtProdFact.Columns.Add(cValTva);

                dsProdFact.Tables.Add(dtProdFact);
            }

            if (bModify)
            {
                dtProdFact = CustomProcedures.GETPRODFACT(iFactId);

                int iNrCrt = 0;
               // double dValoareProd = 0, dTotal = 0;
                foreach (DataRow drProdRecep in dtProdFact.Rows)
                {
                    arrList.Add(Convert.ToInt32(drProdRecep["factprod_idprod"]));
                    iNrCrt = iNrCrt + 1;

                    dValoareTVA = Math.Round(Convert.ToDouble(drProdRecep["factprod_val_tva"]),2) ; // / 100 * Convert.ToDouble(drProdRecep["txtProdPret"]), 2);
                    dValoareFaraTVA = Math.Round(Convert.ToInt32(drProdRecep["factprod_cant"]) * Convert.ToDouble(drProdRecep["factprod_pret"]), 2);

                    gridProduseFact.Rows.Add(Convert.ToString(drProdRecep["factprod_idprod"]), iNrCrt.ToString(), Convert.ToString(drProdRecep["prod_denumire"]), Convert.ToString(drProdRecep["prod_um"]), Convert.ToString(drProdRecep["factprod_cant"]), Convert.ToString(drProdRecep["factprod_pret"]), dValoareFaraTVA, dValoareTVA, false);

                    dTotalFaraTva = dTotalFaraTva + Math.Round(dValoareFaraTVA, 2);
                    dTotalTva = dTotalTva + Math.Round(dValoareTVA, 2);
                    dTotalGeneral = Math.Round(dTotalFaraTva + dTotalTva, 2);

                }

                txtTotalGeneral.Text = dTotalGeneral.ToString();
                txtTotalTVA.Text = dTotalTva.ToString();
                txtTotalFaraTva.Text = dTotalFaraTva.ToString();

            }

            SetControlDataBinding(true);
        }

        private void SetControlDataBinding(bool bClient)
        {
            
            txtFactData.DataBindings.Clear();
            txtFactNumar.DataBindings.Clear();
            txtFactSerie.DataBindings.Clear();
            txtFactMentiuni.DataBindings.Clear();
            txtFactDelegat.DataBindings.Clear();
            txtFactIntocmit.DataBindings.Clear();

            if (bClient)
            {
                txtClBanca.DataBindings.Clear();
                txtClCif.DataBindings.Clear();
                txtClEmail.DataBindings.Clear();
                txtClIBAN.DataBindings.Clear();
                txtClCod.DataBindings.Clear();
                txtClAdresa.DataBindings.Clear();
                txtClRegCom.DataBindings.Clear();
                comboClDenum.DataBindings.Clear();
            }

            txtProdCant.DataBindings.Clear();
            txtProdPret.DataBindings.Clear();
            txtProdTva.DataBindings.Clear();
            txtProdUm.DataBindings.Clear();
            comboProdDen.DataBindings.Clear();

            gridProduseFact.DataBindings.Clear();

            if (bModify)
            {
                //gridProduseNir.DataSource = dsProdFact.Tables["receptii_produs"];

                txtFactData.DataBindings.Add("Value", dsFact.Tables["facturi"], "fact_data");
                txtFactNumar.DataBindings.Add("Text", dsFact.Tables["facturi"], "fact_numar");
                txtFactSerie.DataBindings.Add("Text", dsFact.Tables["facturi"], "fact_serie");
                txtFactMentiuni.DataBindings.Add("Text", dsFact.Tables["facturi"], "fact_mentiuni");
                txtFactDelegat.DataBindings.Add("Text", dsFact.Tables["facturi"], "fact_delegat");
                txtFactIntocmit.DataBindings.Add("Text", dsFact.Tables["facturi"], "fact_intocmit");

            }

            if (bClient)
            {
                dsClienti = new DataSet();
                //SqlDataAdapter daFurnizori = new SqlDataAdapter("SELECT * FROM furnizori ORDER BY furn_denumire ASC", conn);
                SqlDataAdapter daFurnizori = new SqlDataAdapter("SELECT '' AS cl_cif, '' as cl_regc, '' as cl_denumire, '' as cl_adresa, '' as cl_cod, '' as cl_iban, '' as cl_banca, '' as cl_email, '' as cl_data union all select * from clienti ORDER BY cl_denumire ASC", conn);
                daFurnizori.Fill(dsClienti, "clienti");


                /*txtFzBanca.Text = string.Empty;
                txtFzCif.Text = string.Empty;
                txtFzEmail.Text = string.Empty;
                txtFzIBAN.Text = string.Empty;
                txtFzJudet.Text = string.Empty;
                txtFzLocalit.Text = string.Empty;
                txtFzRegCom.Text = string.Empty;*/


                txtClBanca.DataBindings.Add("Text", dsClienti.Tables["clienti"], "cl_banca");
                txtClCif.DataBindings.Add("Text", dsClienti.Tables["clienti"], "cl_cif");
                txtClEmail.DataBindings.Add("Text", dsClienti.Tables["clienti"], "cl_email");
                txtClIBAN.DataBindings.Add("Text", dsClienti.Tables["clienti"], "cl_iban");
                txtClCod.DataBindings.Add("Text", dsClienti.Tables["clienti"], "cl_cod");
                txtClAdresa.DataBindings.Add("Text", dsClienti.Tables["clienti"], "cl_adresa");
                txtClRegCom.DataBindings.Add("Text", dsClienti.Tables["clienti"], "cl_regc");
                //comboFzDenum.DataBindings.Add("SelectedValue", dsClienti.Tables["furnizori"], "furn_cif");

                // Combobox Databinding
                comboClDenum.DataSource = dsClienti;
                comboClDenum.DisplayMember = "clienti.cl_denumire";
                comboClDenum.ValueMember = "clienti.cl_cif";

                crManagerClienti = (CurrencyManager)BindingContext[dsClienti.Tables["clienti"]];

                if (bModify)
                {
                    dsClienti.Tables["clienti"].PrimaryKey = new DataColumn[] { dsClienti.Tables["clienti"].Columns["cl_cif"] };

                    DataRow drfurn = dsClienti.Tables["clienti"].Rows.Find(dsFact.Tables["facturi"].Rows[0]["fact_client_cif"].ToString());
                    comboClDenum.SelectedIndex = dsClienti.Tables["clienti"].Rows.IndexOf(drfurn);
                }
                else
                    comboClDenum.SelectedIndex = -1;
            }

            dsProduse = new DataSet();
            SqlDataAdapter daFactProd = new SqlDataAdapter("SELECT 0 AS prod_id, '' AS prod_cod, '' as prod_um, '' as prod_denumire, null as prod_cota_tva UNION ALL SELECT * FROM produse ORDER BY prod_denumire ASC", conn);
            daFactProd.Fill(dsProduse, "produse");

            txtProdTva.DataBindings.Add("Text", dsProduse.Tables["produse"], "prod_cota_tva");
            txtProdUm.DataBindings.Add("Text", dsProduse.Tables["produse"], "prod_um");
            
            //Combobox databinding
            comboProdDen.DataSource = dsProduse;
            comboProdDen.DisplayMember = "produse.prod_denumire";
            comboProdDen.ValueMember = "produse.prod_id";

            crManagerProd = (CurrencyManager)BindingContext[dsProduse.Tables["produse"]];

            comboProdDen.SelectedIndex = -1;

       }

        private void comboProdDen_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (crManagerProd != null && crManagerProd.Position <= crManagerProd.Count -1 && comboProdDen.SelectedIndex >= 0)
            crManagerProd.Position = comboProdDen.SelectedIndex ;
            txtProdCant.Text = string.Empty;

            if (comboProdDen.SelectedIndex == -1 || comboProdDen.SelectedIndex == 0 )
                txtProdPret.Text = string.Empty;
            else
            {
                SqlCommand cmdStoc = new SqlCommand("SELECT stoc_pret_vanzare FROM STOCURI WHERE stoc_prod_id = " + comboProdDen.SelectedValue, conn);
                SqlDataReader readerStoc = cmdStoc.ExecuteReader();

                while (readerStoc.Read())
                {
                    txtProdPret.Text = readerStoc["stoc_pret_vanzare"].ToString().Replace(".",",") ;
                }

                readerStoc.Dispose();
                readerStoc.Close();
                readerStoc = null;
            }

        }

        private void comboFzDenum_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (crManagerClienti != null && crManagerClienti.Position <= crManagerClienti.Count -1 && comboClDenum.SelectedIndex >= 0)
                crManagerClienti.Position = comboClDenum.SelectedIndex ;
        }

        private void btnProdAdauga_Click(object sender, EventArgs e)
        {
            iNrCrt ++ ;
            string sMsgText = string.Empty;

            if (comboProdDen.Text.Length == 0)
            {
                MessageBox.Show("Introduceti denumirea articolului!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (txtProdCant.Text.Length == 0)
            {
                MessageBox.Show("Introduceti cantitatea!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
           
            if (arrList != null && arrList.IndexOf(comboProdDen.SelectedValue) >= 0)
            {
                MessageBox.Show("Nu puteti adauga acelasi produs de doua ori!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning );
                comboProdDen.SelectedIndex = -1;
                txtProdCant.Text = txtProdPret.Text = txtProdTva.Text = txtProdUm.Text = string.Empty;
                return;
            }
            else
            {
                SqlCommand cmdCant = new SqlCommand("SELECT count(*) AS nr FROM STOCURI WHERE stoc_cant>" + txtProdCant.Text + " AND stoc_prod_id=" + comboProdDen.SelectedValue , conn);
                SqlDataReader readerCant = cmdCant.ExecuteReader();
                int iNr = 0;
                while (readerCant.Read())
                {
                    iNr = (Convert.ToInt32(readerCant["nr"]));
                }
                readerCant.Dispose();
                readerCant.Close();
                readerCant = null;

                if (iNr == 0)
                {
                    MessageBox.Show("Cantitatea de pe stoc este mai mica decat cantitatea introdusa!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }


                arrList.Add(comboProdDen.SelectedValue);
                iNrCrt = gridProduseFact.Rows.Count;
                dValoareTVA = Math.Round(Convert.ToDouble(txtProdTva.Text) / 100 * Convert.ToDouble(txtProdPret.Text), 2);
                dValoareFaraTVA = Math.Round(Convert.ToInt32(txtProdCant.Text) * Convert.ToDouble(txtProdPret.Text), 2);//Math.Round((Convert.ToDouble(txtProdTva.Text)/100 +1) * Convert.ToDouble(txtProdPret.Text));

                gridProduseFact.Rows.Add(comboProdDen.SelectedValue, iNrCrt.ToString(), comboProdDen.Text, txtProdUm.Text, txtProdCant.Text, txtProdPret.Text, dValoareFaraTVA, dValoareTVA, false);

                dTotalFaraTva = dTotalFaraTva + Math.Round(dValoareFaraTVA, 2);
                dTotalTva = dTotalTva + Math.Round(dValoareTVA, 2);
                dTotalGeneral = Math.Round(dTotalFaraTva + dTotalTva, 2);

                txtTotalGeneral.Text = dTotalGeneral.ToString();
                txtTotalTVA.Text = dTotalTva.ToString();
                txtTotalFaraTva.Text = dTotalFaraTva.ToString();

                DataRow drProdFact;
                drProdFact = dtProdFact.NewRow();
                drProdFact["factprod_idprod"] = comboProdDen.SelectedValue;
                drProdFact["factprod_cant"] = Convert.ToInt32(txtProdCant.Text);
                drProdFact["factprod_pret"] = Convert.ToDouble(txtProdPret.Text);
                drProdFact["factprod_val_tva"] = dValoareTVA;
                dtProdFact.Rows.Add(drProdFact);

                comboProdDen.SelectedIndex = -1;

                txtProdCant.Text = txtProdUm.Text = string.Empty;

                SetControlDataBinding(false);

            }
        }

        private void btnProdDel_Click(object sender, EventArgs e)
        {
            double dTotalGeneralTemp = 0, dTotalTvaTemp = 0, dTotalFaraTvaTemp = 0;
            for (int i = 0; i < gridProduseFact.Rows.Count - 1; i++)
                    if ((bool)gridProduseFact.Rows[i].Cells[gridProduseFact.ColumnCount - 1].FormattedValue)
                    {
                        dTotalFaraTvaTemp = dTotalFaraTvaTemp + Math.Round(Convert.ToDouble(gridProduseFact.Rows[i].Cells["colProdValFaraTva"].Value), 2);
                        dTotalTvaTemp = dTotalTvaTemp + Math.Round(Convert.ToDouble(gridProduseFact.Rows[i].Cells["colProdTva"].Value ), 2);
                        //dTotal = Math.Round(dTotalTemp - dTotalTvaTemp - dTotalGeneralTemp, 2);

                        dtProdFact.Rows.RemoveAt(gridProduseFact.CurrentRow.Index);
                        arrList.Remove(gridProduseFact.Rows[i].Cells["colProdId"].Value);
                        gridProduseFact.Rows.RemoveAt(gridProduseFact.CurrentRow.Index);
                    }
            dTotalFaraTva = Convert.ToDouble(txtTotalFaraTva.Text) - dTotalFaraTvaTemp;
            dTotalTva = Convert.ToDouble(txtTotalTVA.Text) - dTotalTvaTemp ;
            dTotalGeneral = Math.Round (Convert.ToDouble(txtTotalGeneral.Text) - dTotalFaraTvaTemp - dTotalTvaTemp,2);

            for (int i = 0; i < gridProduseFact.Rows.Count - 1; i++)
            {
                gridProduseFact.Rows[i].Cells["colProdNrCrt"].Value = i + 1;
            }
            txtTotalGeneral.Text = Math.Round(dTotalGeneral, 2).ToString();
            txtTotalTVA.Text = dTotalTva.ToString();
            txtTotalFaraTva.Text = dTotalFaraTva.ToString();

            SetControlDataBinding(false);
        }


        private void btnSalveaza_Click(object sender, EventArgs e)
        {
            SqlCommand sqlComm;
            int nrcrt;
            try
            {
                string sMsg = string.Empty;

                if (comboClDenum.SelectedIndex == -1 || comboClDenum.Text.Trim().Length == 0)
                {
                    sMsg = " Client ";
                    goto msgErr;
                }

                if (bModify)
                {
                    CustomProcedures.UPDATEFACTURI(iFactId,
                                                    txtFactSerie.Text,
                                                    Convert.ToInt32(txtFactNumar.Text),
                                                    txtFactData.Value,
                                                    txtClCif.Text,
                                                    txtFactDelegat.Text,
                                                    txtFactIntocmit.Text,
                                                    txtFactMentiuni.Text,
                                                    Convert.ToDouble(txtTotalFaraTva.Text),
                                                    Convert.ToDouble(txtTotalTVA.Text),
                                                    Convert.ToDouble(txtTotalGeneral.Text)
                                                    );

                    sqlComm = new SqlCommand("DELETE FROM factura_produs WHERE factprod_idfact = " + iFactId.ToString(), conn);
                    sqlComm.ExecuteNonQuery();

                    string strProdRecep = "INSERT INTO factura_produs(factprod_idfact, factprod_nrcrt, factprod_idprod, " +
                                                                     "factprod_cant, " +
                                                                     "factprod_pret, factprod_val_tva ) " +
                                                                     "VALUES " +
                                                                     "(@idrec, @nrcrt, @idprod, " +
                                                                     " @cant, " +
                                                                     " @pret, @val_tva)";


                    nrcrt = 1;
                    foreach (DataRow dr in dtProdFact.Rows)
                    {
                        sqlComm = new SqlCommand(strProdRecep, conn);

                        sqlComm.Parameters.Add("@idrec", iFactId);
                        sqlComm.Parameters.Add("@nrcrt", nrcrt);
                        sqlComm.Parameters.Add("@idprod", Convert.ToInt32(dr[0]));
                        sqlComm.Parameters.Add("@cant", Convert.ToInt32(dr[1]));
                        sqlComm.Parameters.Add("@pret", Convert.ToDouble(dr[2]));
                        sqlComm.Parameters.Add("@val_tva", Convert.ToDouble(dr[3]));
                        sqlComm.ExecuteNonQuery();

                        try
                        {
                            CustomProcedures.UPDATESTOCURI(Convert.ToInt32(dr[0]), Convert.ToInt32(dr[1]), 0, 2);
                        }
                        catch
                        {

                        }

                        nrcrt++;
                    }

                }
                else
                {
                    if (sSerieNr == txtFactSerie.Text.Trim() + txtFactNumar.Text.Trim()) return;
                    CustomProcedures.INSERTFACTURI(txtFactSerie.Text,
                                                    Convert.ToInt32(txtFactNumar.Text),
                                                    txtFactData.Value,
                                                    txtClCif.Text,
                                                    txtFactDelegat.Text,
                                                    txtFactIntocmit.Text,
                                                    txtFactMentiuni.Text,
                                                    Convert.ToDouble(txtTotalFaraTva.Text),
                                                    Convert.ToDouble(txtTotalTVA.Text),
                                                    Convert.ToDouble(txtTotalGeneral.Text),
                                                    dsFirma.Tables["firma"].Rows[0]["firma_cif"].ToString()
                                                    );

                    sqlComm = new SqlCommand("SELECT @@IDENTITY AS NewId", conn);
                    SqlDataReader reader = sqlComm.ExecuteReader();
                    int idrec = 0;
                    while (reader.Read())
                    {
                        idrec = Convert.ToInt32(reader["NewId"]);
                    }

                    reader.Dispose();
                    reader.Close();

                    string strProdRecep = "INSERT INTO factura_produs(factprod_idfact, factprod_nrcrt, factprod_idprod, " +
                                                                      "factprod_cant, factprod_pret, " +
                                                                      "factprod_val_tva ) " +
                                                                      "values " +
                                                                      "(@idrec, @nrcrt, @idprod, " +
                                                                      " @cant, @pret, " +
                                                                      " @val_tva)";


                    nrcrt = 1;

                    foreach (DataRow dr in dtProdFact.Rows)
                    {
                        sqlComm = new SqlCommand(strProdRecep, conn);

                        sqlComm.Parameters.Add("@idrec", idrec);
                        sqlComm.Parameters.Add("@nrcrt", nrcrt);
                        sqlComm.Parameters.Add("@idprod", Convert.ToInt32(dr[0]));
                        sqlComm.Parameters.Add("@cant", Convert.ToInt32(dr[1]));
                        sqlComm.Parameters.Add("@pret", Convert.ToDouble(dr[2]));
                        sqlComm.Parameters.Add("@val_tva", Convert.ToDouble(dr[3])); 
                        
                        sqlComm.ExecuteNonQuery();
                        nrcrt++;
                        try
                        {
                            CustomProcedures.UPDATESTOCURI(Convert.ToInt32(dr[0]), Convert.ToInt32(dr[1]), 0, 2);
                        }
                        catch
                        {

                        }
                    }

                  
                    string sUpdFirma = "UPDATE TOP(1) firma SET firma_fact_ultimnr = " + txtFactNumar.Text.Trim();
                    //sUpdFirma = sUpdFirma + " FROM (SELECT TOP (1) * FROM firma ORDER  BY firma_data desc) AS t1 ";
                    sUpdFirma = sUpdFirma + " WHERE firma_data in (SELECT TOP (1) firma_data FROM firma ORDER  BY firma_data desc)";

                    SqlCommand updComm = new SqlCommand(sUpdFirma, conn);

                    
                    SqlDataReader readerFirma = updComm.ExecuteReader();
                    readerFirma.Close();
                    readerFirma = null;
                    iFactId = idrec;

                  
                }
                sSerieNr = txtFactSerie.Text.Trim() + txtFactNumar.Text.Trim();
                MessageBox.Show("Salvarea s-a efectuat cu succes!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            msgErr: MessageBox.Show("Pentru adaugarea unui Facturi, campul" + sMsg + "trebuie completat!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Operatiunea s-a efectuat cu errori! Datele nu au fost salvate.", "", MessageBoxButtons.OK , MessageBoxIcon.Error );  
            }
        }

        public static Form GetSingletonInstance(SqlConnection conection)
        {
            if (_singletonInstance == null || _singletonInstance.IsDisposed)
            {
                connStatic = conection;
                _singletonInstance = new frmFactura(connStatic);
            }
            return _singletonInstance;
        }


        public void SetKeyValues(int iFactId)
        {
            this.iFactId = iFactId;
            bModify = true;
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            CustomProcedures.conn = conn;
            SqlDataAdapter daPrintFact = CustomProcedures.ReportGETFACTURI(iFactId);//dsFacttii.Tables["receptii"];
            dsFacturi dsResult = new dsFacturi();
            daPrintFact.Fill(dsResult);
            if (!bModify && dsResult.Tables[1].Rows.Count == 0) MessageBox.Show("Atentie, datele de pe formular nu au fost salvate! Documentul afisat nu contine date.", "", MessageBoxButtons.OK,  MessageBoxIcon.Warning);   

            frmReport formReport = new frmReport("C:\\Users\\Iulia\\Documents\\Visual Studio 2008\\Projects\\StockMentor\\StockMentor\\ReportFacturi.rpt", dsResult);
            
            formReport.Show();
           
        }

        private void btnNou_Click(object sender, EventArgs e)
        {
            iFactId = -1;

            dValoareFaraTVA = dValoareTVA = dTotalTva = dTotalFaraTva = dTotalGeneral = 0;

            gridProduseFact.Rows.Clear();
            dtProdFact.Rows.Clear();

            txtFactDelegat.Text = txtFactIntocmit.Text = txtFactMentiuni.Text = txtTotalFaraTva.Text = txtProdTva.Text = txtTotalGeneral.Text = txtTotalTVA.Text = string.Empty;

            dsFirma.Dispose();
            dsFirma = null;
            dsFirma = new DataSet();
                    
            daFirma.Fill(dsFirma, "firma");

            txtFactSerie.Text = dsFirma.Tables["firma"].Rows[0]["firma_fact_serie"].ToString();
            txtFactNumar.Text = (Convert.ToInt32(dsFirma.Tables["firma"].Rows[0]["firma_fact_ultimnr"]) + 1).ToString();

            sSerieNr = string.Empty; //txtFactSerie.Text.Trim() + txtFactNumar.Text.Trim();

            dtProdFact.Rows.Clear();
            arrList.Clear();
            txtTotalGeneral.Text = string.Empty;
            SetControlDataBinding(true);
        }

        private void btnClAdauga_Click(object sender, EventArgs e)
        {

            Form form = null;

            form = frmEditClienti.GetSingletonInstance(this.conn);

            ((frmEditClienti)form).SetKeyValues(string.Empty, this);
            form.StartPosition = FormStartPosition.CenterScreen;
            form.ShowDialog();
            form.BringToFront(); 
        }
        public void CallBack(string sDenum)
        {
            SetControlDataBinding(true);
            comboClDenum.SelectedIndex = comboClDenum.FindStringExact(sDenum);
        }

        private void txtProdPret_Leave(object sender, EventArgs e)
        {
            if (((TextBox)sender).Text.Trim () != string.Empty && !IsPositiveNumber(((TextBox)sender).Text.Trim ()))
            {
                MessageBox.Show("Introduceti o valoare valida pentru pret!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtProdPret.Focus();
            }
        }

        public bool IsPositiveNumber(String strNumber)
        {
            Regex objPattern = new Regex("^([1-9][0-9]*(\\,{0,1})?|(0\\,))[0-9]*$");

            return objPattern.IsMatch(strNumber);
        }

    }
}
